<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="header-left">
        <h2>🔗 Link Chat</h2>
        <span class="status" :class="{ connected: isConnected }">
          {{ isConnected ? '● 已连接' : '○ 未连接' }}
        </span>
      </div>
      <div class="header-right">
        <span class="username">{{ username }}</span>
        <button @click="handleLogout" class="logout-button">退出</button>
      </div>
    </div>

    <div class="chat-body">
      <!-- 用户列表侧边栏 -->
      <div class="users-sidebar">
        <div class="sidebar-header">
          <h3>在线用户 ({{ users.length }})</h3>
        </div>
        <div class="users-list">
          <TransitionGroup name="slide-up">
            <div
              v-for="user in users"
              :key="user.id"
              class="user-item"
              :class="{ self: user.id === userId }"
            >
              <span class="user-avatar">{{ user.username[0] }}</span>
              <span class="user-name">{{ user.username }}</span>
              <span v-if="user.id === userId" class="self-tag">你</span>
            </div>
          </TransitionGroup>
        </div>
      </div>

      <!-- 消息区域 -->
      <div class="messages-area">
        <div class="messages-list" ref="messagesContainer">
          <TransitionGroup name="slide-up">
            <div
              v-for="(msg, index) in messages"
              :key="index"
              class="message-item"
              :class="{ system: msg.type === 'system', self: msg.userId === userId }"
            >
              <div v-if="msg.type === 'system'" class="system-message">
                {{ msg.content }}
              </div>
              <div v-else class="user-message">
                <div class="message-avatar">{{ msg.username[0] }}</div>
                <div class="message-content">
                  <div class="message-header">
                    <span class="message-username">{{ msg.username }}</span>
                    <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
                  </div>
                  <div class="message-text">{{ msg.content }}</div>
                </div>
              </div>
            </div>
          </TransitionGroup>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <form @submit.prevent="handleSendMessage" class="input-form">
            <input
              v-model="messageInput"
              type="text"
              placeholder="输入消息..."
              :disabled="!isConnected"
              class="message-input"
            />
            <button
              type="submit"
              :disabled="!isConnected || !messageInput.trim()"
              class="send-button"
            >
              发送
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useWebSocket } from '../composables/useWebSocket.js'

const props = defineProps({
  username: String,
  userId: String,
})

const emit = defineEmits(['logout'])

const WS_URL = 'ws://localhost:8080/ws'
const { isConnected, messages, users, connect, disconnect, sendMessage } = useWebSocket(WS_URL)

const messageInput = ref('')
const messagesContainer = ref(null)

onMounted(() => {
  connect(props.username, props.userId)
})

watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const handleSendMessage = () => {
  if (messageInput.value.trim() && isConnected.value) {
    sendMessage(messageInput.value)
    messageInput.value = ''
  }
}

const handleLogout = () => {
  disconnect()
  emit('logout')
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp * 1000)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
  })
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  height: 100%;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  font-size: 1.5rem;
  font-weight: 700;
}

.status {
  font-size: 0.85rem;
  padding: 5px 12px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
}

.status.connected {
  background: rgba(76, 175, 80, 0.3);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-weight: 600;
  font-size: 1rem;
}

.logout-button {
  padding: 8px 20px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 8px;
  font-weight: 500;
}

.logout-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

.chat-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.users-sidebar {
  width: 260px;
  background: #f8f9fa;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-header h3 {
  font-size: 1rem;
  color: #333;
  font-weight: 600;
}

.users-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  margin-bottom: 5px;
  border-radius: 10px;
  transition: all 0.2s ease;
}

.user-item:hover {
  background: white;
}

.user-item.self {
  background: #e3f2fd;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 0.9rem;
}

.user-name {
  flex: 1;
  font-size: 0.9rem;
  color: #333;
}

.self-tag {
  background: #667eea;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.75rem;
}

.messages-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.messages-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-item {
  margin-bottom: 20px;
}

.system-message {
  text-align: center;
  color: #999;
  font-size: 0.85rem;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 15px;
  display: inline-block;
  margin: 0 auto;
}

.user-message {
  display: flex;
  gap: 12px;
}

.message-item.self .user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  flex-shrink: 0;
}

.message-item.self .message-avatar {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-item.self .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.message-username {
  font-weight: 600;
  font-size: 0.9rem;
  color: #333;
}

.message-time {
  font-size: 0.75rem;
  color: #999;
}

.message-text {
  background: #f0f0f0;
  padding: 12px 16px;
  border-radius: 15px;
  word-wrap: break-word;
  line-height: 1.5;
}

.message-item.self .message-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  background: white;
}

.input-form {
  display: flex;
  gap: 10px;
}

.message-input {
  flex: 1;
  padding: 14px 18px;
  border-radius: 25px;
  border: 2px solid #e0e0e0;
  font-size: 1rem;
}

.message-input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.send-button {
  padding: 14px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 25px;
  font-weight: 600;
  font-size: 1rem;
}

.send-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.send-button:not(:disabled):hover {
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}
</style>
